package com.link.play.fit.ai.pushWorker

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Context.NOTIFICATION_SERVICE
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.link.play.fit.ai.R
import com.link.play.fit.ai.kv.AuthCache.mealsAlarmCount
import com.link.play.fit.ai.ui.SplashAc
import com.link.play.fit.ai.utils.WeekDatesUtil.getNextMondayDelay
import java.util.concurrent.TimeUnit
import kotlin.random.Random

class WeeklyPushWorker(context: Context, params: WorkerParameters) : Worker(context, params) {

    override fun doWork(): Result {
        sendNotification()
        scheduleNextMondayPush() // 每次执行后调度下周任务
        return Result.success()
    }

    private fun sendNotification() {
        mealsAlarmCount+=1
        val channelId = "kcal_weight_channel_id"
        val channelName = "kcal_weight_channel_name"

        val notificationManager =
            applicationContext.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel =
                NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
            channel.lockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC
            channel.setShowBadge(true)
            notificationManager.createNotificationChannel(channel)
        }
        val intent = Intent(applicationContext, SplashAc::class.java)
        val pendingIntent = PendingIntent.getActivity(applicationContext, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        // 创建通知（具体实现参考前文）
        val notification = NotificationCompat.Builder(applicationContext, channelId)
//            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setContentTitle(applicationContext.getString(R.string.app_name))
            .setContentIntent(pendingIntent)
            .setContentText(applicationContext.getString(R.string.make_sure_to_log_your_weight_track_your_progress_for_this_week))
            .setSmallIcon(R.mipmap.ic_notification)
            .setColor(applicationContext.getColor(R.color.color_17D995))
            .build()
        notificationManager.notify(Random.nextInt(), notification)

    }

    private fun scheduleNextMondayPush() {
        val delay = getNextMondayDelay()

        val workRequest = OneTimeWorkRequestBuilder<WeeklyPushWorker>()
            .setInitialDelay(delay, TimeUnit.MILLISECONDS)
            .build()

        WorkManager.getInstance(applicationContext)
            .enqueueUniqueWork(
                "weekly_monday_push",
                ExistingWorkPolicy.REPLACE,
                workRequest
            )
    }
}